﻿using UnityEngine;
using System.Collections;

public class Shootable : MonoBehaviour {

	public float hp = 5;
	public float difficulty_factor = 0f;
	public GameObject die_fx;
	public GameObject create_on_destroy;
	
	public Material hit_flash_material;
	private Material original_material;
	private float hitflash = 0f;
	private Renderer ren;
	private SpriteRenderer sprren;
	
	public int level = 0;
	
	
	void Start()
	{
		if(difficulty_factor>0f)
		{
			level = Random.Range (0,(int)(Game.starting_difficulty*difficulty_factor));
			hp += level/3;
			transform.localScale*=(1f+(float)(level)/50);
		}
		
		
		// hitflash
		ren = gameObject.GetComponent<Renderer>();
		sprren = gameObject.GetComponent<SpriteRenderer>();
		
		if(ren == null)
			ren = gameObject.GetComponentInChildren<Renderer>();
		if(sprren == null)
			sprren = gameObject.GetComponentInChildren<SpriteRenderer>();
		
		if(ren)
			original_material = ren.material;
		if(sprren)
			original_material = sprren.material;
		
		if(ren)
		{
			if(original_material.HasProperty("_MainTex"))
				hit_flash_material.SetTexture("_MainTex",original_material.GetTexture("_MainTex"));
		}
		
		
		

	}
	
	void Update()
	{
		if(hit_flash_material!=null)
		{
			if(hitflash>0f)
			{
				hitflash -= Time.deltaTime;
				
				if(hitflash <= 0f)
				{
					if(ren)
						ren.material = original_material;
					if(sprren)
						sprren.material = original_material;
				}
			}
		}
	}
	
	void OnCollisionEnter2D(Collision2D c)
	{
		if(c.gameObject.tag == "Bullet")
		{
			Destroy(c.gameObject);
			
			hp-=c.gameObject.GetComponent<Bullet>().damage;
			
			if(hit_flash_material!=null)
			{
				hitflash = 0.05f;

				if(ren)
					ren.material = hit_flash_material;
				if(sprren)
					sprren.material = hit_flash_material;
			}
			
			if(hp<=0)
			{
			
				ShockWave();
				
				if(die_fx != null)
				{
					GameObject explosion = Instantiate(die_fx,transform.position,transform.rotation)as GameObject;
					Destroy (explosion,explosion.particleSystem.startLifetime);
				}
				if(create_on_destroy != null)
				{
					GameObject item = Instantiate(create_on_destroy,transform.position,transform.rotation)as GameObject;
				}
				
				Destroy (gameObject);
			}
		}
	}
	
	void ShockWave()
	{
		Rigidbody2D[] gos = FindObjectsOfType<Rigidbody2D>() as Rigidbody2D[];
		
		foreach(Rigidbody2D go in gos)
		{
			if(go != null)
			{
				
				float dist = Vector3.Distance(transform.position, go.transform.position);
				
				if(dist>0f)
				{
					if(go.transform.tag == "Bullet")
					{
						Destroy (gameObject);
					}
					else
					{
						Vector3 dir = go.transform.position - transform.position;
						go.velocity = dir.normalized * 10f / (1f+dist);
					}
				}
			}
		}
	}
}

